package com.tc.have_a_tired.service;

import com.tc.have_a_tired.config.ConfigManager;
import com.tc.have_a_tired.ui.ReminderWindow;
import com.tc.have_a_tired.ui.RestCountdownWindow;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * 休息提醒服务类
 * 负责管理定时器和触发提醒
 */
public class RestReminderService {

    private ScheduledExecutorService scheduler;
    private ScheduledFuture<?> scheduledTask;
    private int currentInterval;

    /**
     * 启动提醒服务
     */
    public void start() {
        if (scheduler == null || scheduler.isShutdown()) {
            scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
                Thread t = new Thread(r, "RestReminderThread");
                t.setDaemon(true);
                return t;
            });
        }

        currentInterval = ConfigManager.getReminderInterval();
        scheduleNextReminder();
    }

    /**
     * 停止提醒服务
     */
    public void stop() {
        if (scheduledTask != null && !scheduledTask.isCancelled()) {
            scheduledTask.cancel(false);
        }
        if (scheduler != null && !scheduler.isShutdown()) {
            scheduler.shutdown();
        }
    }

    /**
     * 更新提醒间隔（动态调整）
     */
    public void updateInterval() {
        int newInterval = ConfigManager.getReminderInterval();
        if (newInterval != currentInterval) {
            // 取消当前任务
            if (scheduledTask != null && !scheduledTask.isCancelled()) {
                scheduledTask.cancel(false);
            }
            // 使用新间隔重新调度
            currentInterval = newInterval;
            scheduleNextReminder();
        }
    }

    /**
     * 调度下一次提醒
     */
    private void scheduleNextReminder() {
        scheduledTask = scheduler.schedule(() -> {
            // 在EDT线程中显示提醒窗口
            java.awt.EventQueue.invokeLater(() -> {
                showReminder();
            });
            // 注意：这里不再立即调度下一次提醒
            // 下一次提醒将在倒计时结束后通过 onCountdownFinished 回调触发
        }, currentInterval, TimeUnit.MINUTES);
    }

    /**
     * 显示提醒窗口
     */
    private void showReminder() {
        int interval = ConfigManager.getReminderInterval();
        int restDuration = ConfigManager.getRestDuration();
        String message = ConfigManager.getFinalMessage(interval, restDuration);

        ReminderWindow reminderWindow = new ReminderWindow(message, restDuration, () -> {
            // 用户点击"知道了"后的回调
            // 显示休息倒计时窗口
            showRestCountdown(restDuration);
        });
        reminderWindow.setVisible(true);
    }

    /**
     * 显示休息倒计时窗口
     * 
     * @param restDurationMinutes 休息时长（分钟）
     */
    private void showRestCountdown(int restDurationMinutes) {
        RestCountdownWindow countdownWindow = new RestCountdownWindow(
                restDurationMinutes,
                () -> {
                    // 倒计时结束后的回调
                    // 开始下一轮工作时间
                    scheduleNextReminder();
                });
        countdownWindow.setVisible(true);
    }

    /**
     * 获取当前提醒间隔
     */
    public int getCurrentInterval() {
        return currentInterval;
    }
}
